package com.example.match.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.match.common.BaseResponse;
import com.example.match.common.ErrorCode;
import com.example.match.common.ResultUtils;
import com.example.match.exception.BusinessException;
import com.example.match.model.domain.Team;
import com.example.match.model.domain.User;
import com.example.match.model.domain.UserTeam;
import com.example.match.model.dto.TeamQuery;
import com.example.match.model.request.TeamAddRequest;
import com.example.match.model.request.TeamJoinRequest;
import com.example.match.model.request.TeamQuitRequest;
import com.example.match.model.request.TeamUpdateRequest;
import com.example.match.model.vo.TeamUserVO;
import com.example.match.service.TeamService;
import com.example.match.service.UserService;
import com.example.match.service.UserTeamService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 雨后天晴
 * @version 1.0
 * @since 2024/10/8 18:58
 */
@RestController
@RequestMapping("/team")
@Tag(name = "队伍模块")
public class TeamController {
    @Resource
    private UserService userService;

    @Resource
    private TeamService teamService;
    @Resource
    private UserTeamService userTeamService;

    @Operation(summary = "创建队伍")
    @PostMapping
    public BaseResponse<Long> createTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if (teamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        long teamId = teamService.createTeam(team, loginUser);
        return ResultUtils.success(teamId);
    }

    @Operation(summary = "解散队伍")
    @DeleteMapping("/{id}")
    public BaseResponse<Boolean> deleteTeam(@PathVariable long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.deleteTeam(id, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除队伍失败");
        }
        return ResultUtils.success(true);
    }

    @Operation(summary = "更新队伍")
    @PutMapping
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        if (teamUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.updateTeam(teamUpdateRequest, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新队伍失败");
        }
        return ResultUtils.success(true);
    }

    @Operation(summary = "根据id获取队伍")
    @GetMapping("/{id}")
    public BaseResponse<Team> getTeamById(@PathVariable long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "队伍不存在");
        }
        return ResultUtils.success(team);
    }

    @Operation(summary = "获取队伍列表")
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> listTeams(@ParameterObject TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean isAdmin = userService.isAdmin(request);
        // 1. 查询队伍列表
        List<TeamUserVO> teams = teamService.listTeams(teamQuery, isAdmin);
        // 2. 判断当前用户是否已加入队伍
        List<Long> teamIdList = teams.stream().map(TeamUserVO::getId).collect(Collectors.toList());
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            User loginUser = userService.getLoginUser(request);
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            userTeamQueryWrapper.in("teamId", teamIdList);
            List<UserTeam> userTeams = userTeamService.list(userTeamQueryWrapper);
            Set<Long> hasJoinTeamIdSet = userTeams.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            teams.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception ignored) {}
        // 3. 查询加入队伍的用户信息（人数）
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("teamId", teamIdList);
        List<UserTeam> userTeams = userTeamService.list(queryWrapper);
        // 4. 队伍 id => 加入队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeams = userTeams.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teams.forEach(team -> {
            team.setHasJoinNum(teamIdUserTeams.getOrDefault(team.getId(), new ArrayList<>()).size());
        });
        return ResultUtils.success(teams);
    }

    @Operation(summary = "分页获取队伍列表")
    @GetMapping("/page")
    public BaseResponse<Page<Team>> listTeamsByPage(@ParameterObject TeamQuery teamQuery) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(team, teamQuery);
        Page<Team> page = new Page<>(teamQuery.getCurrent(), teamQuery.getSize());
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> teamPage = teamService.page(page, queryWrapper);
        return ResultUtils.success(teamPage);
    }

    @Operation(summary = "加入队伍")
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.joinTeam(teamJoinRequest, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "加入队伍失败");
        }
        return ResultUtils.success(true);
    }

    @Operation(summary = "获取当前用户加入的队伍")
    @GetMapping("/current")
    public BaseResponse<List<TeamUserVO>> listTeamsByUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        TeamQuery teamQuery = new TeamQuery();
        List<TeamUserVO> teams = teamService.listTeamsByUser(loginUser);
        return ResultUtils.success(teams);
    }

    @Operation(summary = "退出队伍")
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.quitTeam(teamQuitRequest, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "退出队伍失败");
        }
        return ResultUtils.success(true);
    }

}
